import { saveTemplateId } from '@/service/index/default'
import { generateSignature } from '@/utils/signatureV'
import { ecgMin } from '@/service/config/servicePort'
const baseUrl = import.meta.env.VITE_SERVER_BASEURL
export const getSn = (key) => {
  const sn = uni.getStorageSync('sn')
  return !key ? sn : sn[key]
}

export const clearSn = () => {
  uni.removeStorageSync('sn');
}

export const setSn = (obj) => {
  uni.setStorageSync('sn', obj);
}


export const getClientTime = (key) => {
  const sn = uni.getStorageSync('clientTime')
  return !key ? sn : sn[key]
}

export const clearClientTime = () => {
  uni.removeStorageSync('clientTime');
}

export const setClientTime = (obj) => {
  uni.setStorageSync('clientTime', obj);
}


export const isLoginEdPage = () => {
  const user = uni.getStorageSync('user')
  const isLogin = !!user.phoneNumber && !!user.userId
  if (isLogin) return true
  // 后退到首页刷新页面
  var pages = getCurrentPages();
  var currentPage = pages[pages.length - 1];
  if (currentPage.data.refreshIfNeeded) return true
  return false
}

export const isLoginEd = () => {
  const user = uni.getStorageSync('user')
  return !!user.phoneNumber && !!user.userId
}

export const getUser = (key) => {
  const user = uni.getStorageSync('user')
  return !key ? user : user[key]
}

export const clearUser = () => {
  uni.removeStorageSync('user');
}

export const setUser = (obj) => {
  uni.setStorageSync('user', obj);
}

export const setUserKey = (key, value) => {
  const user = uni.getStorageSync('user')
  let setUser = {
    phoneNumber: user.phoneNumber || null,
    isAdmin: user.isAdmin || false,
    userId: user.userId || null,
    avatar: user.avatar || null,
    name: user.name || null,
    loginTime: user.loginTime || '0000001234567'
  }
  setUser[key] = value
  uni.setStorageSync('user', setUser);
}

export const showModal = (params = {}) => {
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...params,
      title: params?.title || '系统提示',
      content: params?.content || '参数无效',
      confirmText: params?.confirmText || '返回',
      showCancel: params?.showCancel || false,
      success: (res) => {
        if (res.confirm) {
          resolve(true); // Promise 成功，表示已成功执行
        } else {
          reject(false); // 如果用户取消了操作，Promise 失败
        }
      },
      fail: () => {
        reject(false); // 如果弹窗出现异常，返回错误信息
      }
    });
  });
}


export const loginJump = (url = '/pages-sub/login/index') => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '提示',
      content: '您还未登录，登录后可继续当前操作',
      showCancel: true,
      cancelText: '暂不登录',
      confirmText: '立即登录',
      confirmColor: '#e50038',
      cancelColor: '#999999',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url })
          resolve(true)
        } else if (res.cancel) {
          resolve(false)
        }
      },
    })
  })
}

export const Re_login = (url = '/pages-sub/login/index') => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '提示',
      content: '登录状态已过期，请重新登录！',
      showCancel: true,
      cancelText: '暂不登录',
      confirmText: '立即登录',
      confirmColor: '#e50038',
      cancelColor: '#999999',
      success: (res) => {
        if (res.confirm) {
          clearUser()
          setSn('')
          uni.navigateTo({ url })
          resolve(true)
        } else if (res.cancel) {
          resolve(false)
        }
      },
    })
  })
}

// U5DqBf_Tjt1U4ZPQ2EVZkwOgnYuHjDZXU7IljsVmK4Q //设备更换提醒
const tmplIds = ['tg3yZVIFMgqk9iv2EnJyL3XHQYBC4cJ9XIPkB_vOGB0'] //服务状态通知
export const subscribe = (userId) => {
  return new Promise((resolve) => {
    wx.requestSubscribeMessage({
      tmplIds,
      success(res) {
        console.log('订阅消息状态：accept代表成功', res)
        if (res[tmplIds[0]] === 'accept') {
          saveTemplateId({ userId, templateId: tmplIds[0] })
          resolve(tmplIds[0])
        } else {
          saveTemplateId({ userId, templateId: '' })
          resolve(false)
        }
      },
      fail(err) {
        saveTemplateId({ userId, templateId: '' })
        resolve(false)
      }
    })
  })
}


export const uploadImg = async (params) => {
  const { filePath, userId } = params
  return new Promise((resolve) => {
    if (!filePath) {
      resolve(false)
      return
    }
    const headSet = generateSignature({ userId }, Date.now(), 'POST')
    uni.uploadFile({
      url: `${baseUrl}${ecgMin}/saveAvatar`, // 上传接口地址
      filePath,
      name: 'file',
      header: {
        ...headSet,
      },
      formData: { userId },
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        resolve(false)
      },
    })
  })
}
